package com.person.jc.service.buy;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.person.jc.service.Service;
import com.person.jc.utils.Utils;

public class BsBuyAuditService extends Service {
	
	public final static BsBuyAuditService me = new BsBuyAuditService();
	
	public List<Record> getList(Map<String, Object> map){
		String temp = "";
		List<Object> params = new ArrayList<Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT t.*,t1.kind_name use_to_name,t2.kind_name status_name,(SELECT SUM(unit_price*num) FROM bs_buy_product WHERE buy_id = t.buy_id) total_price , ");
		sql.append(" t3.user_name buy_user_name,t4.user_name director_name,t5.user_name manager_name FROM bs_buy_apply t");
		sql.append(" left join ts_code_kind_data t1 ON t.buy_use = t1.kind_code AND t1.type_code='use_to' ");
		sql.append(" left join ts_code_kind_data t2 ON t.status = t2.kind_code AND t2.type_code='buy_status'  ");
		sql.append(" left join ts_user t3 on t.buy_user = t3.user_id ");
		sql.append(" left join ts_user t4 on t.director = t4.user_id ");
		sql.append(" left join ts_user t5 on t.manager = t5.user_id ");
		sql.append(" where 1 = 1 ");
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("status")))){
			sql.append(" and t.status = ? ");
			params.add(temp);
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("supplierName")))){
			sql.append(" and t.supplier like ? ");
			params.add("%" + temp + "%");
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("buyUser")))){
			sql.append(" and t3.user_name like ? ");
			params.add("%" + temp + "%");
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("startDate")))){
			sql.append(" and date_format(t.req_date,'%Y-%m-%d') >= ?");
			params.add(temp);
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("endtDate")))){
			sql.append(" and date_format(t.req_date,'%Y-%m-%d') <= ?");
			params.add(temp);
		}
		sql.append(" order by t.buy_id desc");
		return Db.find(sql.toString(), Utils.getObjParam(params));
		
	}
	
	public void saveDirAudit(Map<String, Object> map){
		String sql = "update bs_buy_apply set director = ? ,director_date = now() where buy_id = ?";
		Db.update(sql, map.get("optUser"), map.get("buyId"));
		super.setCRUD("采购审核", "U", "主管审核采购单："+map.get("buyId"));
	}
	
	public void saveMgrAudit(Map<String, Object> map){
		String sql = "update bs_buy_apply set manager = ? ,manager_date = now(), status = 20 where buy_id = ?";
		Db.update(sql, map.get("optUser"), map.get("buyId"));
		super.setCRUD("采购审核", "U", "经理审核采购单："+map.get("buyId"));
	}
}
